package com.base.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.demo.utils.ReflectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

public class ExcelMain {

    public static void main(String[] args) {

        List<ExportDemo> demoList = new ArrayList<>();
        ExportDemo.Good gbs = ExportDemo.Good.builder().goodName("果倍爽").goodId(1).build();
        ExportDemo.Good zhanma = ExportDemo.Good.builder().goodName("战马").goodId(1).build();
        List<ExportDemo.Good> goods = new ArrayList<>();
        goods.add(gbs);
        goods.add(zhanma);
        ExportDemo.Tuan tuan1 = ExportDemo.Tuan.builder().name("饮料团").endDate(new Date()).goods(goods).build();
        ExportDemo.Tuan tuan2 = ExportDemo.Tuan.builder().name("蔬菜团").endDate(new Date()).goods(goods).build();
        List<ExportDemo.Tuan> tuans = new ArrayList<>();
        tuans.add(tuan1);
        tuans.add(tuan2);
        demoList.add(ExportDemo.builder().orderId("No01").orderName("分拣单").tuans(tuans).build());
        demoList.add(ExportDemo.builder().orderId("No02").orderName("出库单").tuans(tuans).build());


        String title="title";
        ExportParams exportParams = new ExportParams(title, "user");

        exportParams.setTitleHeight((short) 20);
        exportParams.setType(ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ExportDemo.class, demoList);


        try {
            //文件写到了项目根目录
            OutputStream os = new FileOutputStream("text_new1.xls");
            workbook.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //todo 半成品
    private static void initRowData(HSSFRow row, HSSFCell[] cells , String[] fieldNames, int fieldIndex, String trimPrefix, Object obj) {

        boolean mergeFlag;
        boolean createRow = false;
//        mergeCells;
        Map<String,Boolean> donePreFix = new HashMap<>();
        for (int cellIndex = fieldIndex ;cellIndex < fieldNames.length; cellIndex++){
            String fieldName = fieldNames[cellIndex];
            if(!fieldName.startsWith(trimPrefix)){
                continue;
            }
            //是否前面的操作处理了该cell
            if(fieldName.contains(".") && donePreFix.containsKey(fieldName.substring(0,fieldName.lastIndexOf(".")+1))){
                continue;
            }
            Object value;
            String realFieldName = fieldName.replace(trimPrefix, "");
            if(!realFieldName.contains(".")){
                value = ReflectionUtil.invokeGetterMethod(obj, realFieldName);
                row.getCell(cellIndex).setCellValue(value == null ? "" : value.toString());
                for (int i = 0; i < cellIndex; i++) {
                    System.out.print("  ");
                }
                System.out.println(String.format(" %s -- %s %s %s",row.getRowNum(),cellIndex,fieldName,value));

                createRow = true;
            }else {
                String[] fields = realFieldName.split("\\.");
                Object obj_ = ReflectionUtil.invokeGetterMethod(obj, fields[0]);
                if(obj_ == null || !(obj_ instanceof List)){
                    continue;
                }
                mergeFlag = true;
                List list = (List) obj_;

                for (int k = 0; k < list.size(); k++) {
                    String newTrimPrefix = StringUtils.join(trimPrefix,fields[0],".");
                    //开始新的遍历对象属性
                    donePreFix.put(newTrimPrefix,true);

                    if(k != 0){
                        row = row.getSheet().createRow(row.getRowNum() + 1);
                        cells = getCells(row,fieldNames.length + 1);
                    }
                    initRowData(row,cells,fieldNames,cellIndex,newTrimPrefix,list.get(k));
                    //执行完成，创建新行
                    if(k != 0 && k == list.size()-1){
                        row = row.getSheet().createRow(row.getRowNum() + 1);
                        cells = getCells(row,fieldNames.length + 1);
                    }

                }
            }

        }
        //合并单元格
//        CellRangeAddress cellRange = new CellRangeAddress(startRow.getRowNum(), endRow.getRowNum(), 0, 0);
//        sheets[sheetNum].addMergedRegion(cellRange);
    }

    /**
     * @Description: 创建内容行的每一列(附加一列序号)
     */
    public static HSSFCell[] getCells(HSSFRow contentRow, int num) {
        HSSFCell[] cells = new HSSFCell[num + 1];
        for (int i = 0, len = cells.length; i < len; i++) {
            cells[i] = contentRow.createCell(i);
        }
        return cells;
    }
}
